#include <linux/module.h>
#include <linux/gpio/consumer.h>
#include <linux/init.h>
#include <linux/i2c.h>
#include <linux/gpio/consumer.h>
#include <linux/interrupt.h>

#define CONFIG_GPIOLIB 1
#define dev_name "my-touch"

static struct gpio_desc *reset;
static struct gpio_desc *touch;

static irqreturn_t tp_interput_handler (int irq, void *dev_id){
    printk("tp_interput_handler\n");
    return IRQ_HANDLED;
};

static struct i2c_device_id mytp_id[] = {
    {dev_name, 0},
    { }
};
static int mytp_probe(struct i2c_client *client, const struct i2c_device_id *id){
    int ret = 0;
    // char buf = 0x33;
    printk("mytp_probe\n");
    
    reset = gpiod_get_optional(&client->dev, "reset", GPIOD_OUT_HIGH);
    touch = gpiod_get_optional(&client->dev, "touch", GPIOD_OUT_HIGH);
    // gpiod_optional_get(reset, "reset", GPIOD_OUT_HIGH);
    // gpiod_optional_get(touch, "touch", GPIOD_OUT_HIGH);
     if(ret < 0){
        printk("gpiod_optional_get failed\n");
        return ret;
    }else{
        printk("gpiod_optional_get success\n");
        printk("reset = %d\n", gpiod_get_value(reset));
        printk("touch = %d\n", gpiod_get_value(touch));
    }
    ret = gpiod_to_irq(touch);
    if (ret < 0) {
        printk("gpiod_to_irq failed\n");
        return ret;
    }else{
        printk("gpiod_to_irq success\n");
        printk("irq = %d\n", ret);
    }
    
    ret = request_irq(ret, tp_interput_handler, IRQF_TRIGGER_RISING, "touch", NULL);
    if (ret < 0) {
        printk("request_irq failed\n");
        return ret;
    }else{
        printk("request_irq success\n");
    }
    

    return 0;
}
static int mytp_remove(struct i2c_client *client){
    printk("mytp_remove\n");
    free_irq(gpiod_to_irq(touch), NULL);
    gpiod_put(reset);
    gpiod_put(touch);
    
    return 0;
}

static struct i2c_driver driver={
    .driver = {
        .name = dev_name,
        .owner = THIS_MODULE,
        // .id_table = mytp_id,
    },
    .probe = mytp_probe,
    .remove = mytp_remove,
    .id_table = mytp_id,
};

static int __init mytp_init(void){
    int ret = 0;
    // 分配空间
    // driver = kmalloc(sizeof(driver),GFP_KERNEL);
    // i2c_init
    // 注册
    ret = i2c_add_driver(&driver);
    if(ret < 0){
        printk("i2c_add_driver failed\n");
        goto error1;
    }
    printk("mytp_init\n");
    return ret;
error1:
    // kfree(driver);
    return ret;
}

static void __exit mytp_exit(void){
    free_irq(gpiod_to_irq(touch), NULL);
    gpiod_put(reset);
    gpiod_put(touch);
    i2c_del_driver(&driver);
    printk("mytp_exit\n");
}


module_init(mytp_init);
module_exit(mytp_exit);
MODULE_AUTHOR("WLZ");
MODULE_LICENSE("GPL");
